#pragma once

#include <iostream>
#include <cerrno>
#include <cstring>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"
#include "LockGuard.hpp"
#include "Comm.hpp"
#include "nocopy.hpp"

const uint16_t defaultport = 8888;
const int defaultbacklog = 1;
const int defaultsize = 1024;


class TcpServer : public nocopy 
{

public:
    TcpServer(uint16_t port = defaultport)
        : _port(port), _isruning(false)
    {
    }
    void Init()
    {
        // 1. 创建文件细节
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            lg(Fatal, "create socket errror , errno : %d strerror : %s\n", errno, strerror(errno));
            exit(Socket_Err);
        }

        // 固定写法，解决一些少量的bind失败的问题 -- TODO
        int opt = 1;
        setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));

        lg(Debug, "create socket success , sockfd : %d\n", _listensock);
        // 2.bind 网络信息
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = INADDR_ANY;

        if (::bind(_listensock, SOCKADDR_IN_TO_SOCKADDR(&server), sizeof(server)) != 0)
        {
            lg(Fatal, "Bind errror , errno : %d strerror : %s\n", errno, strerror(errno));
            exit(Bind_Err);
        }
        lg(Debug, "Bind success , sockfd : %d\n", _listensock);

        // 3. 设置socket为监听状态，tcp特有的
        if (listen(_listensock, defaultbacklog) != 0)
        {
            lg(Fatal, "listen socket errror , errno : %d strerror : %s\n", errno, strerror(errno));
            exit(Listen_Err);
        }
    }

    
    void Service(int sockfd)
    {
        char buffer[defaultsize];
        while (true)
        {
            int n = read(sockfd, buffer, sizeof(buffer));
            if (n > 0)
            {
                buffer[n] = 0;
                lg(Info, "received a message : %s \n", buffer);
                std::string massage = "Server echo# ";
                massage += buffer;
                write(sockfd, massage.c_str(), massage.size());
            }
            else if (n == 0)
            {
                lg(Info, "client quit.....\n");
                break;
            }
            else
            {
                lg(Error, "read success , errno : %d ,  strerror : %s\n", errno, strerror(errno));
                break;
            }
        }
    }

    void Start()
    {
        _isruning = true;
        while (_isruning)
        {
            // 获取新链接fd
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensock, SOCKADDR_IN_TO_SOCKADDR(&peer), &len);
            if (sockfd < 0)
            {
                lg(Error, "accept error, errno : %d  ,strerror : %s\n", errno, strerror(errno));
                continue;
            }
            lg(Debug, "accept success , get n new sockfd : %d", sockfd);

            // 在这里提供服务 （多种）
            Service(sockfd);
            close(sockfd);
            lg(Info,"file descriptor close , close : %d",sockfd);
        }
    }
    ~TcpServer()
    {

    }

private:
    uint16_t _port;
    int _listensock;
    bool _isruning;
};
